import React, { Component } from 'react';
import { Form, Modal, Table } from 'antd';
import OrgSelect from '../../components/OrgSelect';
import { inject, observer } from 'mobx-react';

@inject('store', 'roleStore')
@observer
class RoleDialog extends Component {
  selectRef = React.createRef();
  state = { selectedRows: null, visible: false };
  onOrgOnload = data => {
    this.setState({ visible: data.visible });
    this.props.roleStore.orgOnload(data);
  };

  onOrgSelect = value => {
    this.props.roleStore.orgSelect(value);
  };

  onOk = () => {
    this.props.store.addUserRole(this.state.selectedRows);
    this.props.roleStore.closeRoleDialog();
  };

  render() {
    const { visible, roles, allRoles } = this.props.roleStore.roleDialogData;
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.state.selectedRows = selectedRows;
      },
      getCheckboxProps: record => {
        for (let role of roles) {
          if (role.id != record.id) continue;
          return ({ disabled: true });
        }
        return ({ disabled: false });
      },
    };
    const columns = [
      { title: '角色名称', dataIndex: 'name', key: 'name', width: 150 },
      { title: '描述', dataIndex: 'remark', key: 'remark', width: 150 }];
    const layout = { labelCol: { span: 3 }, wrapperCol: { span: 21 } };

    return (<Modal title='可选角色' width={620}
                   visible={visible}
                   destroyOnClose={true}
                   onOk={() => this.onOk()}
                   onCancel={() => this.props.roleStore.closeRoleDialog()}>
      <Form ref={this.selectRef} {...layout} >
        <Form.Item name='orgId' label='所属机构' noStyle={!this.state.visible}>
          <OrgSelect onSelect={key => this.onOrgSelect(key)}
                     onload={data => this.onOrgOnload(data)}/>
        </Form.Item>
      </Form>
      <Table rowKey="id" size={'small'} rowSelection={rowSelection}
             dataSource={allRoles} columns={columns}
             pagination={false}/>
    </Modal>);
  }
}

export default RoleDialog;
